package com.woniuxy.filter;

import com.woniuxy.enums.TokenStatusEnum;
import com.woniuxy.jwt.JWTUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class JWTGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //从请求头获取key为Authorization的值，就是我们的JWT：json web token；
        List<String> authorization = exchange.getRequest().getHeaders().get("Authorization");

        if(authorization != null){
            //得到token
            String token = authorization.get(0);
            //校验token时候有效，如果有效果就放行
            TokenStatusEnum verify = JWTUtils.verify(token);
            if (verify.equals(TokenStatusEnum.TOKEN_SUCCESS)) {
                return chain.filter(exchange);//放行
            }else if(verify.equals(TokenStatusEnum.TOKEN_EXPIRE)){
                //如果过期
                exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                return Mono.error(new ArithmeticException("长时间未操作，请重新登录"));
            }
        } else {
            //说明没有token，判断 时候登录请求
            if ("/auth/login".equals(exchange.getRequest().getPath().toString())) {
                return chain.filter(exchange);//放行
            }else {
                //判断该链接是否需要登录认证或者某个角色！
            }
        }
        return chain.filter(exchange);//放行
    }
    /**
     * 优先级排序
     *  hlf
     *
     * @return int
     */

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
